package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.model.dto.SettingKVDTO;
import com.mai4j.maiadmin.service.SettingService;
import com.mai4j.maiadmin.support.IdProvider;
import com.mai4j.maiadmin.support.JooqProvider;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

import static com.mai4j.maiadmin.generated.Tables.SETTING;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class SettingServiceImpl implements SettingService {

    @Transactional
    @CacheEvict(value = "data", key = "'settings:' + #code")
    @Override
    public void save(String code, SettingKVDTO settingKV) {
        JooqProvider.dsl().deleteFrom(SETTING).where(SETTING.CODE.eq(code)).execute();
        for (Map.Entry<String, Object> entry : settingKV.entrySet()) {
            JooqProvider.dsl().insertInto(SETTING).columns(
                    SETTING.SETTING_ID,
                    SETTING.CODE,
                    SETTING.NAME,
                    SETTING.VALUE).values(
                    IdProvider.next(),
                    code,
                    entry.getKey(),
                    String.valueOf(entry.getValue())).execute();
        }
    }

    @Transactional
    @Override
    @Cacheable(value = "data", key = "'settings:' + #code")
    public SettingKVDTO get(String code) {
        SettingKVDTO settingKV = new SettingKVDTO();
        Map<String, String> records = JooqProvider.dsl().select(SETTING.NAME,
                        SETTING.VALUE)
                .from(SETTING)
                .where(SETTING.CODE.eq(code)).fetchMap(SETTING.NAME, SETTING.VALUE);
        settingKV.putAll(records);
        return settingKV;
    }
}
